/* eslint-disable default-case */
/* eslint-disable no-unused-expressions */
import { message } from 'antd';
import {
  getListBillData,
  getUnpaidBillsData,
  deleteBill,
  markData,
  checkCreateBillTask,
  getProgress,
  getCheckCreate,
  getCreateBill,
  getCustNameList,
  mergeBill,
  getDetailData,
  getBillDetailData,
  getRespUserList,
} from '@/services/customerbilling';
import * as service from '@/services/socket';

export default {
  state: {
    expandForm: false,
    activeKey: '1',
    formFieldsValue: {},
    data: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    proBaseList: {},
    proFbList: [],
    proListData: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    isHasTask: false,
    billTaskId: null,
    taskCode: null,
    detailDataInfo: {},
    billDetailDataInfo: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    titType: null,
    resultInfo: {
      // 结果数据必传
      batchName: '生成账单', // 任务名称
      taskCount: 0, // 导入数据
      successCount: 0, // 成功数据
      errorCount: 0, // 失败数据
      batchNo: '', // 批次号
      errorUrl: '/csApi/csBill/downBillException', // 下载错误信息地址
      errorParams: null, // 下载错误数据参数
    },
    showProgress: false,
    progressPercent: 0,
    modalVisible: false,
    respUserList: [],
  },
  effects: {
    // 获取列表
    *getListBill({ payload }, { call, put }) {
      const response = yield call(getListBillData, { ...payload, contId: payload?.contId?.key });
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      yield put({
        type: 'getList',
        payload: {
          data: [],
          currentPage,
          pageSize,
        },
      });
      if (response.success) {
        // eslint-disable-next-line no-unused-expressions
        response.data &&
          response.data.pageRecords &&
          // eslint-disable-next-line array-callback-return
          response.data.pageRecords.map(item => {
            // eslint-disable-next-line no-param-reassign
            item.key = item.billYm + item.custId + item.involvePersonNum + item.billNo;
          });

        yield put({
          type: 'getList',
          payload: {
            data: response.data || [],
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning('列表数据错误：服务端未知错误');
      }
    },

    // 获取未进账单列表
    *getUnpaidBillsList({ payload }, { call, put, select }) {
      const response = yield call(getUnpaidBillsData, { ...payload, contId: payload?.contId?.key });
      const customerbilling = yield select(state => state.customerbilling);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      yield put({
        type: 'getList',
        payload: {
          data: [],
          currentPage,
          pageSize,
        },
      });
      if (response.success) {
        if (customerbilling.activeKey === '2') {
          // eslint-disable-next-line no-unused-expressions
          response.data &&
            response.data.pageRecords &&
            // eslint-disable-next-line array-callback-return
            response.data.pageRecords.map(item => {
              // eslint-disable-next-line no-param-reassign
              item.key = item.custId + item.feeYm;
            });
        }

        yield put({
          type: 'getList',
          payload: {
            data: response.data || [],
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(response.message || '列表数据错误：服务端未知错误');
      }
    },

    // 删除账单
    *deleteBill({ payload }, { call }) {
      const response = yield call(deleteBill, payload);
      return response;
    },

    // 标记已收费
    *markModelData({ payload, callback }, { call }) {
      const response = yield call(markData, payload);
      // eslint-disable-next-line no-unused-expressions
      callback && callback(response);
    },

    // 判断有无账单任务
    *checkCreateBillTask(_, { call, put }) {
      const response = yield call(checkCreateBillTask);
      if (response.success && response.data) {
        if (response.data.taskCode === 3) {
          yield put({
            type: 'updateModelData',
            payload: {
              isHasTask: true,
              billTaskId: response.data.billTaskId,
              taskCode: response.data.taskCode,
            },
          });
        } else {
          yield put({
            type: 'updateModelData',
            payload: {
              isHasTask: false,
            },
          });
        }
      }
      return response;
    },

    // 获取进度数据
    *getProgress({ payload }, { call, put }) {
      const response = yield call(getProgress, payload);
      if (response.success) {
        yield put({
          type: 'updateModelData',
          payload: { progressPercent: response.data.rate },
        });
      }
      return response;
    },

    // 生成账单
    updateCheckCreate: [
      function*({ payload, callback }, { call }) {
        const response = yield call(getCheckCreate, payload);
        callback && callback(response);
      },
      { type: 'throttle', ms: 10000 },
    ],

    // 生成账单
    *updateCreateBill({ payload, callback }, { call }) {
      const response = yield call(getCreateBill, payload);
      callback && callback(response);
    },

    // 合并账单
    *mergebilling({ payload, callback }, { call }) {
      const response = yield call(mergeBill, payload);
      callback && callback(response);
    },

    // 客户名称
    *getCustName({ payload, callback }, { call }) {
      const response = yield call(getCustNameList, payload);
      callback && callback(response);
    },

    // 查看详情
    *detailData({ payload }, { call, put }) {
      const response = yield call(getDetailData, payload);
      if (response.success) {
        yield put({
          type: 'featchDetailData',
          payload: { data: response.data },
        });
      } else {
        message.warning(response.message || '服务器端错误');
      }
    },

    // 查看账单明细
    *billDetailsData({ payload }, { call, put }) {
      const {
        pageArg: { currentPage, pageSize },
      } = payload;

      yield put({
        type: 'featchBillDetailData',
        payload: {
          data: [],
          pagination: {
            currentPage,
            pageSize,
            totalCount: 10,
          },
        },
      });

      const response = yield call(getBillDetailData, payload);
      if (response.success) {
        // eslint-disable-next-line array-callback-return
        response.data.pageRecords.map(item => {
          if (!item.empId) {
            // eslint-disable-next-line no-param-reassign
            item.onceFee.feeAmo = item.oneOffAmo;
            // eslint-disable-next-line no-param-reassign
            item.onceFee.detail = item.detail;
          }
          // eslint-disable-next-line no-param-reassign
          item.key = item.billYm + item.custId + item.empId;
        });
        yield put({
          type: 'featchBillDetailData',
          payload: { data: response.data, currentPage, pageSize },
        });
      } else {
        message.warning(response.message || '获取账单明细失败！');
      }
    },

    // 上传文件:批量进度:获取batchId后获取进度 :batchType：1为生成账单，2为合并账单
    uploadFileWithProgress: [
      function*({ payload: { batchType, params } }, { call, put }) {
        const response = yield call(batchType === 1 ? getCreateBill : mergeBill, params);
        if (response.success) {
          yield put({
            type: 'updateModelData',
            payload: {
              batchId: response.data.batchId,
              progressPercent: 0,
            },
          });
          if (batchType === 1) {
            yield put({
              type: 'updateModelData',
              payload: {
                isHasTask: response.data && response.data.taskCode === 3,
              },
            });
            if (response.data.taskCode === 1) {
              if (response.data && response.data.successProp !== 100) {
                yield put({
                  type: 'updateModelData',
                  payload: {
                    showProgress: true,
                    modalVisible: false,
                  },
                });
                yield call(service.socketChannel, {
                  type: 'sub',
                  data: {
                    to: response.data && (response.data.batchId || response.data),
                    type: 'csBill',
                  },
                });
              } else {
                yield put({
                  type: 'updateBatchTask',
                  payload: response.data,
                });
              }
            } else if (response.data.taskCode === 3) {
              message.warning('当前有账单任务正在生成，请稍后操作！');
            }
          } else if (batchType === 2) {
            if (response.data && response.data.successProp !== 100) {
              yield put({
                type: 'updateModelData',
                payload: {
                  showProgress: true,
                  modalVisible: false,
                },
              });
              yield call(service.socketChannel, {
                type: 'sub',
                data: {
                  to: response.data && (response.data.batchId || response.data),
                  type: 'csBill',
                },
              });
            } else {
              yield put({
                type: 'updateBatchTask',
                payload: response.data,
              });
            }
          }
        } else {
          // 操作失败
          message.warning(`${response.message || '操作失败：服务端错误'}`);
        }
        return response;
      },
      { type: 'throttle', ms: 10000 },
    ],
    // 匹配唯一batchId
    *matchBatchId({ payload }, { put, select }) {
      const { batchId } = yield select(state => state.customerbilling);
      if (batchId === payload.batchId) {
        yield put({
          type: 'updateBatchTask',
          payload,
        });
      }
    },
    // 获取所属客服列表
    *fetchRespUserList({ payload }, { call, put }) {
      const response = yield call(getRespUserList, payload);
      yield put({
        type: 'updateModelData',
        payload: {
          respUserList: [],
        },
      });
      if (response.success && response.data) {
        yield put({
          type: 'updateModelData',
          payload: {
            respUserList: Array.isArray(response.data) ? response.data : [],
          },
        });
      } else {
        message.warning(response.message || '获取所属客服数据：服务端错误');
      }
    },
  },

  reducers: {
    // 列表
    getList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        data: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize },
        },
      };
    },
    // 更新数据
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 详情数据
    featchDetailData(state, { payload }) {
      return {
        ...state,
        detailDataInfo: payload.data,
      };
    },

    featchBillDetailData(
      state,
      {
        payload: { data, pageSize, currentPage },
      }
    ) {
      const newData = data.pageRecords;
      // 福利费用和保险费用表头
      const bnftCol = [];
      const cmpinsCol = [];
      const bnftDet = {};
      const cmpinsDet = {};
      const bnftNmColTemp = [];
      const cmpinNmColTemp = [];
      if (newData && newData.length) {
        newData.map((item, index) => {
          if (!item.empId) {
            newData[index].onceFee.feeAmo = item.oneOffAmo;
            newData[index].onceFee.detail = item.detail;
          }

          Object.keys(item).forEach(temp=> {
            const obj = {}
            // 判断是否是对象且不是空对象
            if(Object.prototype.toString.call(item[temp]) === '[object Object]' && JSON.stringify(item[temp]) !== "{}"){
              // objList.push(temp)
              Object.keys(item[temp]).forEach(temps=> {
                // 首字母大写
                obj[`${temp}${temps.charAt(0).toUpperCase() + temps.substring(1)}`] = item[temp][temps]
              })
              console.log(obj);
              item[temp] = obj
            }
          })

          // 福利费用和保险费用数据处理
          // 福利费用
          item?.bnftAmoList?.forEach?.(elem => {
            // 福利
            // 福利表头
            const bnftColObj = {};
            bnftColObj.name = elem.pdName;
            bnftColObj.value = elem.pdId;
            if (bnftNmColTemp.indexOf(bnftColObj.name) === -1) {
              bnftNmColTemp.push(bnftColObj.name);
              bnftCol.push(bnftColObj);
            }
            // 福利数据
            if (!bnftDet[elem.pdId]) {
              bnftDet[elem.pdId] = elem.amo;
            }
          });
          bnftDet.PD0 = item.bnftAmo; // 福利合计
          // 保险表头
          item?.cmpinsAmoList?.forEach?.(elem => {
            const cmpinsColObj = {};
            cmpinsColObj.name = elem.pdName;
            cmpinsColObj.value = elem.pdId;
            if (cmpinNmColTemp.indexOf(cmpinsColObj.name) === -1) {
              cmpinNmColTemp.push(cmpinsColObj.name);
              cmpinsCol.push(cmpinsColObj);
            }
            // 保险数据
            if (!cmpinsDet[elem.pdId]) {
              cmpinsDet[elem.pdId] = elem.amo;
            }
          });
          cmpinsDet.PD0 = item.cmpinsAmo; // 保险合计
          item.bnftDet = bnftDet;
          item.cmpinsDet = cmpinsDet;
          return true;
        });
        bnftCol.push({ name: '福利合计', value: 'PD0' }); // 福利合计表头
        cmpinsCol.push({ name: '保险合计', value: 'PD0' }); // 保险合计表头
      }
      const list = Array.isArray(data.pageRecords) ? newData : [];
      return {
        ...state,
        billDetailDataInfo: {
          list,
          pagination: { total: data.totalCount, pageSize, current: currentPage },
          bnftCol, // 福利各项产品费用表头
          cmpinsCol, // 保险各项产品费用表头
        },
        titType: data.titType || 1,
      };
    },

    // 更新批量任务数据
    updateBatchTask(state, { payload }) {
      let { resultInfo, modalVisible } = state;
      modalVisible = false;
      if (payload.successProp === 100) {
        if (payload.errorCount) {
          resultInfo.errorParams = {
            billTaskId: payload.batchId,
          };
          resultInfo.errorCount = payload.errorCount || 0;
        }
        resultInfo.taskCount = payload.taskNumber;
        resultInfo.billCount = payload.successCount;
        resultInfo.feeYm =
          payload.feeYm &&
          `${payload.feeYm.toString().substr(0, 4)}-${payload.feeYm.toString().substr(4, 5)}`;
        resultInfo.successCount = payload.successCount;
        resultInfo.taskFlag = payload.taskFlag || 1;
        resultInfo = { ...resultInfo, ...payload };
      }
      return {
        ...state,
        modalVisible,
        progressPercent: payload.successProp,
        resultInfo,
      };
    },
  },
  subscriptions: {
    socket({ dispatch }) {
      return service.listen(action => {
        switch (action.type) {
          case 'csBill':
            dispatch({
              type: 'matchBatchId',
              payload: action.data,
            });
            // 全局保存
            dispatch({
              type: 'publicdata/updateBatchTaskData',
              payload: action.data,
            });
            break;
        }
      });
    },
  },
};
